/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.repository.metric;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.MetricEntity;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

/**
 * 基于Mybatis实现的数据库存储监控信息
 *
 * @author Carpenter Lee
 */
@Component
public class JdbcDaoMetricsRepository implements MetricsRepository<MetricEntity> {

    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @Autowired
    private MetricEntityMapper metricEntityMapper;

    @Override
    public void save(MetricEntity metric){
        if (metric == null || StringUtil.isBlank(metric.getApp())) {
            return;
        }
        readWriteLock.writeLock().lock();
        try{
            metricEntityMapper.save(metric);
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    @Override
    public void saveAll(Iterable<MetricEntity> metrics){
        if (metrics == null) {
            return;
        }
        readWriteLock.writeLock().lock();
        try {
           // metrics.forEach(this::save);
            List<MetricEntity> list = new ArrayList<>();
            metrics.forEach(single ->list.add(single));
            metricEntityMapper.saveAll(list);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    @Override
    public List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime){
        List<MetricEntity> results = new ArrayList<>();
        if (StringUtil.isBlank(app) || StringUtil.isBlank(resource)) {
            return results;
        }
        readWriteLock.readLock().lock();
        try{
            List<MetricEntity> list = metricEntityMapper.queryList(app,resource,startTime,endTime);
            return list;
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    @Override
    public List<String> listResourcesOfApp(String app){
        List<String> results = new ArrayList<>();
        if (StringUtil.isBlank(app)) {
            return results;
        }
        readWriteLock.readLock().lock();
        try{
            //final long minTimeMs = System.currentTimeMillis() - 1000 * 60;
            Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32);
            List<MetricEntity> list = metricEntityMapper.queryList(app,null,-1,-1);
            for(MetricEntity metric : list){
                if(resourceCount.containsKey(metric.getResource())){
                    MetricEntity oldEntity = resourceCount.get(metric.getResource());
                    oldEntity.addPassQps(metric.getPassQps());
                    oldEntity.addRtAndSuccessQps(metric.getRt(), metric.getSuccessQps());
                    oldEntity.addBlockQps(metric.getBlockQps());
                    oldEntity.addExceptionQps(metric.getExceptionQps());
                    oldEntity.addCount(1);
                }else{
                    resourceCount.put(metric.getResource(), MetricEntity.copyOf(metric));
                }
            }
            // Order by last minute b_qps DESC.
            return resourceCount.entrySet()
                    .stream()
                    .sorted((o1, o2) -> {
                        MetricEntity e1 = o1.getValue();
                        MetricEntity e2 = o2.getValue();
                        int t = e2.getBlockQps().compareTo(e1.getBlockQps());
                        if (t != 0) {
                            return t;
                        }
                        return e2.getPassQps().compareTo(e1.getPassQps());
                    })
                    .map(Entry::getKey)
                    .collect(Collectors.toList());
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

}
